// Copyright (C) 2010 Félix Cloutier.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License 2.0 for more details.

// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/

// This file must not be compiled under Windows.
#ifndef _MSC_VER

#include "UContextCoroutine.h"
#include <cstring>

// Since we can't include <ucontext.h> on OS X, let's declare the functions here
extern "C" void makecontext(ucontext_t*, void (*)(), int, ...);
extern "C" int swapcontext(ucontext_t*, const ucontext_t*);
extern "C" int getcontext(ucontext_t*);
extern "C" int setcontext(const ucontext_t*);

namespace LLVMJit
{

UContextCoroutine::UContextCoroutine(UContextCoroutine* that)
{
	memset(&context, 0, sizeof context);
	theOther = that;
}

UContextCoroutine::UContextCoroutine(size_t stackSize)
{
	stack = new unsigned char[stackSize];
	memset(&context, 0, sizeof context);
	context.uc_stack.ss_size = stackSize;
	context.uc_stack.ss_sp = stack;
	theOther = new UContextCoroutine(this);
}

void UContextCoroutine::SetEntryPoint(Coroutine::EntryPoint entryPoint, void* argument)
{
	makecontext(&context, (void(*)())entryPoint, 1, argument);
}

void UContextCoroutine::Yield()
{
	swapcontext(&theOther->context, &context);
}

UContextCoroutine::~UContextCoroutine()
{
	if (stack != NULL)
	{
		delete theOther;
		delete stack;
	}
}

}

#endif // _MSC_VER